_package("alz.core");

_import("alz.core.Plugin");
//_import("alz.core.Template");

/**
 * 模板管理器
 */
_class("TemplateManager", Plugin, function(){
	this._init = function(){
		_super._init.call(this);
		this._hash = {};
	};
	this.create = function(name, app, data){
		_super.create.apply(this, arguments);
		if(data) this.reg(data);
	};
	this.dispose = function(){
		for(var k in this._hash){
			this._hash[k] = "";
			delete this._hash[k];
		}
		_super.dispose.apply(this);
	};
	/**
	 * 检查模版的语法
	 */
	this.checkSyntax = function(xml){
		if(runtime.ie){
			try{
				var xmldoc = new ActiveXObject("Msxml.DOMDocument");
				xmldoc.async = false;
				xmldoc.loadXML(xml);
				//return xmldoc;  //.documentElement
				return true;
			}catch(ex){
				console.error("html代码格式不复合xml语法规范", ex, xml);
				return false;
			}
		}else if(window.DOMParser){
			var p = new DOMParser();
			var xmldoc = p.parseFromString(xml, "text/xml");
			if(xmldoc.documentElement.getElementsByTagName("parsererror").length > 0){
				console.error("html代码格式不复合xml语法规范", xml);
				return false;
			}
			return true;
		}else{
			runtime.error("浏览器不支持xmldom");
			return false;
		}
	};
	this.reg = function(tpls){
		var arr = [];
		for(var k in tpls){
			var v = tpls[k];
			if(v === null){  //和PHP程序约定为模板不存在
				v = '<div style="color:red;">模板(' + k + ')不存在</div>';
				arr.push(k);
			}else{
				this.checkSyntax(v);
			}
			this._hash[k] = v;
		}
		if(arr.length > 0){
			runtime.error("下列这些模板不存在，请检查：" + arr.join(","));
		}
	};
	this.getTpl = function(name){
		if(!(name in this._hash)){
			runtime.error("[ERROR]模版库中没有指定的模板(name=" + name + ")");
			return "";
		}
		return this._hash[name];
	};
	this.renderTpl = function(){
	};
});